package com.ycsj.goldmedalnewconcept.main.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ycsj.common.base.SpKeys;
import com.ycsj.common.http.HttpCallBack;
import com.ycsj.common.http.HttpUtils;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.MessageCountTimer;
import com.ycsj.common.utils.AESOperator;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.cleanedittext.CommonEditText;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.main.bean.CodeInfo;
import com.ycsj.goldmedalnewconcept.main.bean.CommonResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import okhttp3.Call;


/**
 * 重置密码
 * Created by Kevin on 2018/2/13.
 */
public class ResetPasswordActivity extends Activity implements View.OnClickListener {

    //倒计时控件
    private MessageCountTimer timer;
    //手机号
    @BindView(R.id.et_tel)
    CommonEditText mEtTel;
    //验证码
    @BindView(R.id.et_msg)
    CommonEditText mEtMsg;

    //发送验证码
    @BindView(R.id.bt_yzm)
    Button mBtYzm;

    @BindView(R.id.et_newpwd)
    CommonEditText mEtNewpwd;

    //确 认
    @BindView(R.id.bt_commit)
    Button mBtCommit;

    @BindView(R.id.ll_main)
    LinearLayout mLlMain;

    //返回控件
    @BindView(R.id.iv_back)
    ImageView iv_back;

    //角色
    private String role;

    /**
     * AES秘钥
     */
    public String key = "@whb%zw￥yk#0601*";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        setContentView(R.layout.activity_resetpassword);

        //初始化
        init();

        //设置状态栏颜色
        setBar();

        super.onCreate(savedInstanceState);
    }

    protected void init() {

        //初始化视图
        initView();

        //初始化数据
        initData();
    }

    /**
     * 初始化数据的方法
     */
    private void initData() {
        //获取身份角色
        role = SPUtil.getString(this, SpKeys.ROLETYPE);

    }

    /**
     * 初始化视图的方法
     */
    public void initView() {

        mEtTel = findViewById(R.id.et_tel);
        mEtMsg = findViewById(R.id.et_msg);
        mEtNewpwd = findViewById(R.id.et_newpwd);

        mLlMain = findViewById(R.id.ll_main);

        mBtYzm = findViewById(R.id.bt_yzm);
        mBtYzm.setOnClickListener(this);

        mBtCommit = findViewById(R.id.bt_commit);
        mBtCommit.setClickable(false);
        mBtCommit.setOnClickListener(this);

        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        mBtCommit = findViewById(R.id.bt_commit);

        mEtTel.setTextcolor(getResources().getColor(R.color.white));
        mEtMsg.setTextcolor(getResources().getColor(R.color.white));
        mEtNewpwd.setTextcolor(getResources().getColor(R.color.white));
        mEtTel.getEdittext().setHintTextColor(getResources().getColor(R.color.white));
        mEtMsg.getEdittext().setHintTextColor(getResources().getColor(R.color.white));
        mEtNewpwd.getEdittext().setHintTextColor(getResources().getColor(R.color.white));

        mEtTel.getEdittext().setInputType(InputType.TYPE_CLASS_PHONE);
    }


    /**
     * 页面控件的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.bt_yzm:
                //获取验证码
                getYzm();
                UiUtils.hideKeyboard(this);
                break;
            case R.id.bt_commit:
                //确定注册
                doCommitAction();
                break;
            case R.id.iv_back:
                //返回
                finish();
                UiUtils.hideKeyboard(this);
                break;
        }
    }


    /**
     * 点击确定按钮的操作
     */
    private void doCommitAction() {

        //获取手机号
        String tel = mEtTel.getEdittext().getText().toString().trim();

        //获取验证码
        String yzm = mEtMsg.getEdittext().getText().toString().trim();

        //获取输入新的密码
        String pwd = mEtNewpwd.getEdittext().getText().toString().trim();

        //判断非空处理
        if (TextUtils.isEmpty(tel)) {
            SnackbarUtil.ShortSnackbar(mLlMain, "手机号不能为空", 0).show();
            return;
        }

        //判断非空处理
        if (TextUtils.isEmpty(yzm)) {
            SnackbarUtil.ShortSnackbar(mLlMain, "请输入验证码", 0).show();
            return;
        }

        //判断非空处理
        if (TextUtils.isEmpty(pwd)) {
            SnackbarUtil.ShortSnackbar(mLlMain, "密码不能为空", 0).show();
            return;
        }

        // 正则表达式判断密码
        if (!isPassword(pwd)) {
            SnackbarUtil.ShortSnackbar(mLlMain, "请输入6-20位数字和字母的组合", 0).show();
            return;
        }

        //验证码的验证
        submitCode(yzm, tel, pwd);

    }


    /**
     * 提交验证码
     */
    private void submitCode(String yzm, final String tel, final String pwd) {
        CustomDialogManager.show(this, "提交中...");

        Map<String, String> map = new HashMap<>();
        map.put("type", "7");
        map.put("c", tel);
        map.put("role", role + "");
        map.put("sms_id", "0");
        map.put("code", yzm);

        com.ycsj.goldmedalnewconcept.common.http.HttpUtils.post(HttpAddress.SUBMITCODE,
                map, this, new com.ycsj.goldmedalnewconcept.common.http.HttpUtils.CallBack() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //请求失败
                        CustomDialogManager.dissmiss();
                        UiUtils.Toast("网络错误", false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        CommonResponse info = null;
                        try {
                            info = GsonUtil.jsonToBean(response, CommonResponse.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i("test", "数据解析异常");
                        }

                        //请求成功
                        Log.i("test", info.state + "");
                        CustomDialogManager.dissmiss();

                        //判断返回值
                        if ("-1".equals(info.state)) {

                            //没有待验证的验证码数据，需要重新发送新的验证码
                            UiUtils.Toast("验证码失效，请重新发送", false);

                        } else if ("1".equals(info.state)) {

                            //通过
                            register(tel, pwd); // 注册

                        } else if ("2".equals(info.state)) {

                            //验证码不一致（内容比对不一致）
                            UiUtils.Toast("验证码不一致", false);

                        } else if ("3".equals(info.state)) {

                            // 验证码失效（未在发送验证码后5分钟内验证）
                            UiUtils.Toast("验证码失效，请重新发送", false);

                        }
                    }
                });
    }


    /**
     * 发送网络请求注册
     */
    private void register(String tel, String pwd) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "3");

        //加密
        String acc = null;
        String pswd = null;
        try {
            acc = AESOperator.getInstance().encrypt(tel);
            pswd = AESOperator.getInstance().encrypt(pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }


        map.put("acc", acc.trim());
        map.put("role", role + "");
        map.put("pswd", pswd.trim());
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.REGISTER,
                map, new HttpCallBack<CommonResponse>() {

                    @Override
                    public void onSuccess(CommonResponse info) {
                        //请求成功
                        Log.i("test", info.state);

                        //判断返回值
                        if ("200".equals(info.state)) {

                            UiUtils.Toast("密码设置成功", false);
                            finish();
                        } else if ("-1".equals(info.state)) {

                            UiUtils.Toast("服务器异常", false);

                        } else if ("101101".equals(info.state)) {

                            UiUtils.Toast("角色账号不存在", false);

                        } else {
                            UiUtils.Toast("密码重置失败，错误代码" + info.state, false);
                        }
                    }

                    @Override
                    public void onError(String e) {
                        //请求失败
                        CustomDialogManager.dissmiss();
                        UiUtils.Toast("网络错误", false);
                    }
                });
    }


    /**
     * 判断密码的正则
     */
    private boolean isPassword(String pwd) {
        String regExp = ("^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}");
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(pwd);
        return m.matches();

    }


    /**
     * 获取验证码的操作
     */
    public void getYzm() {
        //获取手机号
        String tel = mEtTel.getEdittext().getText().toString().trim();

        //判断非空处理
        if (TextUtils.isEmpty(tel)) {
            SnackbarUtil.ShortSnackbar(mLlMain, "手机号不能为空", 0).show();
            return;
        }

        timer = new MessageCountTimer(mBtYzm,
                getResources().getColor(R.color.coffee),
                getResources().getColor(R.color.white),
                getResources().getDrawable(R.drawable.base_register_code_normal));
        timer.start();

        //修改背景变灰
        mBtYzm.setBackgroundResource(R.drawable.base_register_code_gray);

        //发送网络请求获取服务器的验证码
        yzmHttp(tel);

    }


    /**
     * 发送网络请求获取服务器的验证码
     */
    private void yzmHttp(String tel) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("c", tel);
        map.put("role", role + "");
//        map.put("apptoken",AccountUtils.getToken(this));
        map.put("platform", "2");

        com.ycsj.goldmedalnewconcept.common.http.HttpUtils.post(HttpAddress.CODE,
                map, this, new com.ycsj.goldmedalnewconcept.common.http.HttpUtils.CallBack() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //请求失败
                        CustomDialogManager.dissmiss();
                        UiUtils.Toast("网络错误", false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        CodeInfo info = null;
                        try {
                            info = GsonUtil.jsonToBean(response, CodeInfo.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i("test", "数据解析异常");
                        }

                        //请求成功
                        Log.i("test", info.sms_state + "");

                        //判断返回值
                        if ("0".equals(info.sms_state)) {

                            UiUtils.Toast("验证码已发送至您的手机", false);

                        } else if ("-1".equals(info.sms_state)) {

                            UiUtils.Toast("发送失败，请联系客服", false);

                        } else if ("-2".equals(info.sms_state)) {

                            UiUtils.Toast("验证码五分钟有效,请查阅短信", false);

                        }
                    }

                });
    }


    /**
     * 设置沉浸状态栏的方法,需要在setContentView()之后调用
     */
    private void setBar() {
        //兼容5.0+，状态栏设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else
            //为了沉浸式状态栏 4.4以上才有
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
    }
}
